// pages/index/index.js
import Toast from '@vant/weapp/toast/toast'
import Dialog from '@vant/weapp/dialog/dialog'
import { clearUserLocalStorage, logout } from '../../../../utils/util'
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    user: undefined,
    customer_count: 0, //商户数量
    customer_status: [],
    share_options: [{ text: '全部', value: 0 }],
    current_share_id: 0,
    days_0_new_status: 0,
    days_1_new_status: 0,
    days_30_new_status: 0,
    month_status: {
      order_count: 0,
      order_money: 0.0
    },
    month_new_status: {
      order_count: 0,
      order_money: 0.0
    },
    days_30_status: {
      order_count: 0,
      order_money: 0.0
    },
    days_0_status: {
      order_count: 0,
      order_money: 0.0
    },
    days_1_status: {
      order_count: 0,
      order_money: 0.0
    },
    will_leave: 0,
    paid_rate: { s: 0, h: 0, m: 0, l: 0 },
    today_reg: 0,
    today_new: 0,
    yesterday_reg: 0,
    yesterday_count: 0,
    month_reg: 0,
    month_new: 0,
    recovery: 0,
    not_paid_3_days_count: 0,
    no_order_3_days_count: 0,
    no_order_7_days_count: 0,
    no_order_15_days_count: 0,
    no_order_25_days_count: 0,
    id: 0, //司机id
    username: '', //司机姓名
    phone: '', //司机手机号
    area: '[A区]', //司机区域
    status: 0, //司机状态
    notAfterSalesCount: 0, //未发货区域售后订单数量
    notOrderCount: 0, //未发货区域订单数量
    outAfterSalesCount: 0, //当天已发货售后订单数量
    outOrderCount: 0, //当天已发货订单数量
    bindingOrder: 0, //绑定订单数量
    relieveOrder: 0, //待处理订单数量
    access_token: '' //token
	},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //如果登录缓存过期就跳转登录页面
    let now = new Date().getTime() / 1000
    let expiration_time = wx.getStorageSync('expiration_time')
    let group = wx.getStorageSync('role')
    let current_share_id = wx.getStorageSync('current_share_id')
    if (!current_share_id) {
      current_share_id = 0
    }
    if (group !== '销售员') {
      clearUserLocalStorage()
      expiration_time = 0
    }
    if (now > expiration_time) {
      wx.reLaunch({
        url: '/pages/selectID/selectID'
      })
    }
    let access_token = wx.getStorageSync('access_token')
    let user = wx.getStorageSync('user')
    this.setData({
      access_token: access_token,
      user: user,
      level: user.level,
      current_share_id: current_share_id
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.updateLocation()
  },
  //进入小程序就获取位置变化 插入司机数据库
  updateLocation() {
    let user = wx.getStorageSync('user')
    let access_token = wx.getStorageSync('access_token')
    wx.getLocation({
      type: 'gcj02',
      success(d) {
        wx.request({
          url: app.globalData.API + '/salesmany/index/update-location',
          header: {
            'Content-Type': 'application/json',
            'x-api-key': access_token
          },
          method: 'POST',
          data: {
            id: user.id,
            lat: d.latitude,
            long: d.longitude
          },
          success(res) {
            //console.log(res)
            if (res.data.code === 0) {
              //console.log(res.data.message)
            }
          }
        })
      },
      fail(res) {
        Toast('获取位置失败,请允许获取位置信息~')
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.get_share_list()
    this.getOrderCountByStatus()
    //this.bindingOrderCount()
    //this.relieveOrderCount()
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.monitoring()
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},
  /**
   * 查询司机已经绑定的订单数量
   */
  bindingOrderCount() {
    let this_ = this
    let mall_id = app.globalData.mall_id
    let url = app.globalData.URL
    let id = this.data.id
    let username = this.data.username
    wx.request({
      url: url + '/salesman.Order/queryBinDing',
      method: 'GET',
      data: {
        mall_id,
        id,
        username
      },
      success: res => {
        let data = res.data.data
        //console.log(data)
        if (!data) {
          this_.setData({
            bindingOrder: 0
          })
        } else {
          this_.setData({
            bindingOrder: data.length
          })
        }
      }
    })
  },
  /**
   * 查询司机待处理订单数量
   */
  relieveOrderCount() {
    let this_ = this
    let mall_id = app.globalData.mall_id
    let url = app.globalData.URL
    let id = this.data.id
    let name = this.data.username
    wx.request({
      url: url + '/salesman.Order/abnormalOrderAll',
      method: 'GET',
      data: {
        mall_id,
        id,
        name
      },
      success: res => {
        let data = res.data.data
        //console.log(res)
        if (!data) {
          this_.setData({
            relieveOrder: 0
          })
        } else {
          this_.setData({
            relieveOrder: data.length
          })
        }
      }
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // 自定义加载图标
    Toast.loading({
      duration: 1000,
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner'
    })
    let that = this
    //定时两秒结束
    setTimeout(function () {
      console.log('11')
      //_this.location()
      //_this.monitoring()
      wx.stopPullDownRefresh()
    }, 1000)
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  on_dropdown_change(e) {
    let current_share_id = e.detail
    console.log('--------on_dropdown_change:', current_share_id)
    this.setData({
      current_share_id: current_share_id
    })
    wx.setStorageSync('current_share_id', current_share_id)
    this.getOrderCountByStatus()
  },
  //查询顶部订单数量
  async getOrderCountByStatus() {
    const that = this
    wx.request({
      url: app.globalData.API + '/sales/index/get-customers-status',
      header: {
        'Content-Type': 'application/json',
        'x-api-key': this.data.access_token
      },
      method: 'POST',
      data: {
        current_share_id: that.data.current_share_id
			},

      success: res => {
        if (res.data.code === 200) {
          let data = res.data.data.valid_cps_status
          let sum = 0
          for (let key in data) {
            console.log(key)
            if (data.hasOwnProperty(key)) {
              sum += parseInt(data[key], 10)
            }
          }
          that.setData({
            customer_status: res.data.data.valid_cps_status,
            customer_count: sum,
            month_status: res.data.data.month_status.order_status,
            month_new_status: res.data.data.month_new_status.order_status,
            paid_rate: res.data.data.paid_rate.data,
            days_30_status: res.data.data.days_30_status.order_status,
            days_30_new_status: res.data.data.days_30_new_status.order_status,
            days_0_status: res.data.data.days_0_status.order_status,
            days_0_new_status: res.data.data.days_0_new_status.order_status,
            days_1_status: res.data.data.days_1_status.order_status,
            days_1_new_status: res.data.data.days_1_new_status.order_status,
            will_leave: res.data.data.will_leave.count,
            today_reg: res.data.data.today_reg,
            today_new: res.data.data.today_new,
            yesterday_reg: res.data.data.yesterday_reg,
            yesterday_new: res.data.data.yesterday_new,
            month_reg: res.data.data.month_reg,
            month_new: res.data.data.month_new,
            recovery: res.data.data.recovery,
            not_paid_3_days_count: res.data.data.not_paid_3_days_count,
            no_order_3_days_count: res.data.data.no_order_3_days_count,
            no_order_7_days_count: res.data.data.no_order_7_days_count,
            no_order_15_days_count: res.data.data.no_order_15_days_count,
            no_order_25_days_count: res.data.data.no_order_25_days_count
          })
        } else if (res.data.code === 0) {
          clearUserLocalStorage()
          wx.reLaunch({
            url: '/pages/login/login'
          })
        }
      }
    })
  },
  async get_share_list() {
    const that = this
    wx.request({
      url: app.globalData.API + '/sales/index/get-share-list',
      header: {
        'Content-Type': 'application/json',
        'x-api-key': this.data.access_token
      },
      method: 'POST',
      data: {
        region: '[E区]'
      },
      success: res => {
        if (res.data.code === 200) {
          let share_options = res.data.data
          let default_options = [{ value: 0, text: '全部' }]
          that.setData({
            share_options: default_options.concat(share_options)
          })
        } else if (res.data.code === 0) {
          clearUserLocalStorage()
          wx.reLaunch({
            url: '/pages/login/login'
          })
        }
      }
    })
  },
  //手机扫一扫查看订单信息
  async scanCode() {
    wx.scanCode({
      success(res) {
        let order_no = res.result
        if (!order_no || !/^[0-9a-zA-Z]*$/g.test(order_no)) {
          wx.showModal({
            title: '温馨提示',
            content: '请扫正确的订单号',
            showCancel: false
          })
          return false
        }
        console.log(order_no)
        //let order_no = '20230905011334497403';
        wx.p.request({
          url: app.globalData.API + '/salesmany/index/get-order-id',
          header: {
            'Content-Type': 'application/json',
            'x-api-key': this.data.access_token
          },
          method: 'POST',
          data: {
            order_no: order_no //传递商城id
          },
          success(res) {
            if (res.data.code === 200) {
              wx.setStorageSync('order_no' + order_no, res.data.data)
              wx.navigateTo({
                url: '/templates/salesman/pages/sweep/sweep?order_no=' + order_no
              })
            } else if (res.data.code === 0) {
              clearUserLocalStorage()
              wx.reLaunch({
                url: '/pages/login/login'
              })
            }
          },
          fail() {
            wx.showToast({
              title: '扫码异常',
              icon: 'error',
              duration: 2000
            })
          }
        })
      },
      fail() {
        console.log('扫码异常')
      }
    })
  },
  BindOrderByScan: function () {
    let that = this
    wx.request({
      url: app.globalData.API + '/salesmany/index/get-undelivered-count',
      header: {
        'Content-Type': 'application/json',
        'x-api-key': this.data.access_token
      },
      method: 'POST',
      data: {
        sub_days: 1,
        delivery_man_id: 3 //that.data.user.id,
      },
      success: res => {
        if (res.data.code === 200) {
          if (res.data.data.count > 0) {
            Toast('请先完成昨天已绑定的订单!')
            return false
          } else {
            let that = this
            wx.scanCode({
              success(res) {
                let order_no = res.result
                if (!order_no || !/^[0-9a-zA-Z]*$/g.test(order_no)) {
                  wx.showModal({
                    title: '温馨提示',
                    content: '请扫正确的订单号',
                    showCancel: false
                  })
                  return false
                }
                console.log(order_no)
                //let order_no = '20230905011334497403';
                wx.p.request({
                  url: app.globalData.API + '/salesmany/index/get-order-id',
                  header: {
                    'Content-Type': 'application/json',
                    'x-api-key': this.data.access_token
                  },
                  method: 'POST',
                  data: {
                    order_no: order_no //传递商城id
                  },
                  success(res) {
                    if (res.data.code === 200) {
                      wx.setStorageSync('order_no' + order_no, res.data.data)
                      wx.navigateTo({
                        url: '/templates/salesman/pages/binding/binding',
                        success(res) {
                          // 通过eventChannel向被打开页面传送数据
                          res.eventChannel.emit('orderAll', dataStr)
                        }
                      })
                    } else if (res.data.code === 0) {
                      clearUserLocalStorage()
                      wx.reLaunch({
                        url: '/pages/login/login'
                      })
                    }
                  },
                  fail() {
                    wx.showToast({
                      title: '扫码异常',
                      icon: 'error',
                      duration: 2000
                    })
                  }
                })
              },
              fail() {
                console.log('扫码异常')
              }
            })
          }
        } else if (res.data.code === 0) {
          clearUserLocalStorage()
          wx.reLaunch({
            url: '/pages/login/login'
          })
        }
      }
    })
  },
  //查看商户信息
  view_customer() {
    wx.navigateTo({
      url: '/templates/salesman/pages/customer/customer'
      //   success: res=>{
      //       res.eventChannel.emit('orderAll',dataStr)
      //   }
    })
  },
  //根据司机id 和 司机姓名 查询已绑定订单
  bindingOrder() {
    let id = this.data.id //获取司机id
    let username = this.data.username //获取司机姓名
    //根据司机id和姓名查询未完成的订单
    wx.request({
      url:
        app.globalData.URL +
        '/salesman.Order/queryBinDing?id=' +
        id +
        '&username=' +
        username +
        '&mall_id=' +
        app.globalData.mall_id,
      method: 'GET',
      success: res => {
        if (res.data.code === 0) {
          let dataStr = JSON.stringify(res.data.data)
          wx.navigateTo({
            url: '/templates/salesman/pages/bindingorder/bindingorder'
            //   success: res=>{
            //       res.eventChannel.emit('orderAll',dataStr)
            //   }
          })
        } else {
          Toast('错误')
        }
      }
    })
  },
  view_statistics() {
    // temp disable statistics data. the data is not useful
    wx.navigateTo({
      url: '/templates/salesman/pages/statistics/statistics'
      //   success: res=>{
      //       res.eventChannel.emit('orderAll',dataStr)
      //   }
    })
  },
  //退出功能
  logout() {
    Dialog.confirm({
      title: '账号退出',
      message: '您确定要退出当前账号？'
    })
      .then(() => {
        clearUserLocalStorage()
        setTimeout(() => {
          wx.reLaunch({
            url: '/pages/login/login'
          })
        }, 1000)
      })
      .catch(() => {
        // 取消退出
        Toast('取消退出~')
      })
  },
  //监测账号登录状态
  monitoring() {
    console.log('我在监控账号状态')
    let mall_id = app.globalData.mall_id
    var role = wx.getStorageSync('means')
    if (role) {
      wx.request({
        url: app.globalData.URL + '/Login/loginStatus',
        method: 'GET',
        data: {
          mall_id,
          id: role.id
        },
        success(res) {
          //console.log(res)
          if (res.data.data.status === 0) {
            wx.showToast({
              title: '账户异常~ 请联系管理员',
              icon: 'none',
              duration: 3000 //持续的时间
            })
            clearUserLocalStorage()
            wx.reLaunch({
              url: '/pages/login/login'
            })
          }
        }
      })
    }
  }
})
